package structure;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.UnknownHostException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.Historique;
import local.ctl.ctlCpu;
import local.ctl.ctlHisto;
import local.ctl.ctlMemory;
import local.ctl.ctlProcessus;
import rmi.CtlCache;
import shared.Cpu;
import shared.Memory;
import shared.ProcessList;

/**
 *
 * @author chatelai
 */
@WebServlet(name = "Action", urlPatterns = {"/action"})
public class Dispatcher extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if (getServletContext().getAttribute("cache") == null) {
            getServletContext().setAttribute("cache", new CtlCache());
        }
        try {


            if (request.getParameter("delete") != null) {
                ctlHisto.clear();
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }
        } catch (SQLException exe) {
            request.setAttribute("error", "<b>ERREUR </b>impossiblede supprimer l'historique (<i>" + exe.getClass() + "</i>) ");

        }
        try {
            if ((request.getParameter("action") != null) && (request.getParameter("rmi") != null) && (request.getParameter("view") != null)) {


                if (request.getParameter("action").equals("process")) {
                    ProcessList processList;

                    processList = ((CtlCache) getServletContext().getAttribute("cache")).getMonito(request.getRemoteAddr(), request.getParameter("rmi")).getProcessusReal();
                    ctlProcessus.save(request.getParameter("rmi"), processList);
                    request.setAttribute("processList", processList);
                    getServletContext().getRequestDispatcher("/view.jsp").forward(request, response);

                }
                if (request.getParameter("action").equals("memory")) {

                    Memory mem = ((CtlCache) getServletContext().getAttribute("cache")).getMonito(request.getRemoteAddr(), request.getParameter("rmi")).getMemoryReal();
                    ctlMemory.save(request.getParameter("rmi"), mem);
                    request.setAttribute("mem", mem);
                    getServletContext().getRequestDispatcher("/view.jsp").forward(request, response);

                }
                if (request.getParameter("action").equals("cpu")) {

                    Cpu cpu = ((CtlCache) getServletContext().getAttribute("cache")).getMonito(request.getRemoteAddr(), request.getParameter("rmi")).getCpuReal();
                    ctlCpu.save(request.getParameter("rmi"), cpu);
                    request.setAttribute("cpu", cpu);
                    getServletContext().getRequestDispatcher("/view.jsp").forward(request, response);



                }
            }
        } catch (Exception ex) {
            if ((ex instanceof UnknownHostException) || ((ex instanceof NotBoundException))) {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("error", "<b>ERREUR </b>impossible de ce connecter au serveur " + request.getParameter("rmi") + " <i>" + ex.getClass() + "</i>+ :");
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }
            if (ex instanceof RemoteException) {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("error", "<b>ERREUR </b>impossible de ce contacter le service monitoring au serveur " + request.getParameter("rmi") + " (<i>" + ex.getClass() + "</i>)");
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }

            if (ex instanceof java.rmi.ConnectException) {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("error", "<b>ERREUR </b>impossible de ce contacter le service monitoring au serveur " + request.getParameter("rmi") + " (<i>" + ex.getClass() + "</i>)  ");
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }
            if (ex instanceof com.mysql.jdbc.exceptions.jdbc4.CommunicationsException) {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("error", "<b>ERREUR </b>impossible de ce communiquer avec la base de données  (<i>" + ex.getClass() + "</i>)  ");
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }
            if (ex instanceof SQLException) {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("error", "<b>ERREUR </b>impossible de ce sauvegarder les inforamtions d'inventaire en base de donées (<i>" + ex.getClass() + "</i>) ");
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }
            if (ex instanceof NotBoundException) {
                Logger.getLogger(Dispatcher.class.getName()).log(Level.SEVERE, null, ex);
                 request.setAttribute("error", "<b>ERREUR </b>impossible de ce connecter au serveur " + request.getParameter("rmi") + " <i>" + ex.getClass() + "</i>+ : ");
               
                getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
            }
        }


        try {
            if (request.getParameter("histo") != null) {
                if (!request.getParameter("rmi").equals("")) {

                    request.setAttribute("historique", ctlHisto.getlist(request.getParameter("rmi")));
                    getServletContext().getRequestDispatcher("/historique.jsp").forward(request, response);

                } else {
                    request.setAttribute("warn", "<b>warning</b> veuillez remplir le champ IP");
                    getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);

                }
            }

            if (request.getParameter("action").equals("detailledHisto")) {
                Historique myHisto = ctlHisto.createHistorique(request.getParameter("serv"), request.getParameter("type"), request.getParameter("date"), Integer.parseInt(request.getParameter("id")));
                ctlHisto.getObject(myHisto);
                request.setAttribute("myhisto", myHisto);
                getServletContext().getRequestDispatcher("/historique.jsp").forward(request, response);
            }
        } catch (SQLException ex) {
            request.setAttribute("error", "<b>ERREUR </b>impossible de récuperer les inforamtions d'historique dans la base de données (<i>" + ex.getClass() + "</i>) ");
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        }










    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
